<?php
namespace Tbf\Bundle\TbfBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * 命令行password hash函数调用(生成mock数据里面的加密密码用)
 */
class PasswordHashCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('tbf:password_hash')
            ->setDescription('call password_hash()')
            ->addArgument('password')
            ->addOption('algo',null,null,'algo [bcrypt]')
            ->addOption('cost',null,InputOption::VALUE_REQUIRED)
            ->addOption('measure-time');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!function_exists('password_hash')){
            throw new \Exception('you do not have function password_hash.'.
                'Need php >= 5.5.0 or a package named "ircmaxell/password-compat".');
        }
        $algo_map = array(
            'bcrypt'=>PASSWORD_BCRYPT
        );
        $password = $input->getArgument('password');
        if ($password===null){
            throw new \Exception('require password argument');
        }
        if ($input->getOption('algo')!==false) {
            $algo = $input->getOption('algo');
        } else {
            $algo = 'bcrypt';
        }
        $algo = $algo_map[$algo];
        if ($input->getOption('cost')!==null) {
            $cost = $input->getOption('cost');
        } else {
            $cost = 13;
        }
        $is_measure_time = $input->getOption('measure-time')!==false;
        if ($is_measure_time) {
            $b = microtime(true);
        }
        $ret = password_hash($password,$algo,array('cost'=>$cost));
        if ($is_measure_time) {
            $e = microtime(true);
        }
        $output->writeln($ret);
        if ($is_measure_time) {
            $output->writeln('time: '.($e-$b));
        }
    }
}
